package com.mbyte.easy.rest.login;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mbyte.easy.common.controller.BaseController;
import com.mbyte.easy.user.entity.User;
import com.mbyte.easy.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author wangzhen
 * @title: LoginController
 * @projectName easy
 * @description: 用户登录接口
 * @date 2020/7/27 10:22 下午
 */

@RestController
@RequestMapping("rest/login")
public class LoginController extends BaseController {
    @Autowired
    private IUserService userService;

    @Resource
    private CacheManager cacheManager;

    /**
     * 登录验证
     * @param username 用户名
     * @param password 密码
     * @return
     */

    @GetMapping
    public Map<String, Object> index(@RequestParam(value = "username") String username, @RequestParam(value = "password") String password){
        Map<String , Object> map = new HashMap<>();
        User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUserName , username));
        if(user != null && user.getPassword().equals(password)){
            Cache cache = cacheManager.getCache("serviceCacheToken");
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //放入缓存
            cache.put(uuid, user);

            map.put("uuid",uuid);
            map.put("msg","success");
            return map;
        }
        map.put("msg","用户名或密码不正确");
        return map;
    }

    /**
     * 根据token加载用户信息
     * @param token 令牌
     * @return
     */
    @GetMapping("/loadUser")
    public Map<String, Object> loadUser(@RequestParam(value = "token") String token){
        Cache cache = cacheManager.getCache("serviceCacheToken");
        Map<String , Object> map = new HashMap<>();
        User user = cache.get(token, User.class);
        if(user != null){
            map.put("user",user);
            map.put("msg","success");
            return map;
        }
        map.put("msg","令牌已失效！");
        return map;
    }


}
